#include "aerWindow.hpp"
#include "../aerOpenGL.hpp"


namespace aer {

const Display Window::sDisplay_GL20_800x600(800, 600, 24, 8, 2, 0);
const Display Window::sDisplay_GL20_720p(1280, 720, 24, 8, 2, 0);
const Display Window::sDisplay_GL33_800x600(800, 600, 24, 8, 3, 3);
const Display Window::sDisplay_GL33_720p(1280, 720, 24, 8, 3, 3);
const Display Window::sDisplay_GL42_720p(1280, 720, 24, 8, 4, 2);

Window::Window( const Display &display, const char *title)
  : m_display(display),
    m_bClosed(false)
{
  sf::ContextSettings settings;

  settings.depthBits          = display.depthBits;
  settings.stencilBits        = display.stencilBits;
  settings.antialiasingLevel  = 0u;
  settings.majorVersion       = display.majorVersion;
  settings.minorVersion       = display.minorVersion;
  
  sf::Uint32 styles = sf::Style::None;
  if (display.bFullscreen) styles |= sf::Style::Fullscreen;
  if (display.bResizable)  styles |= sf::Style::Resize;
  if (display.bBorder)     styles |= sf::Style::Titlebar;
  if (display.bClose)      styles |= sf::Style::Close;
  
  m_handle.create( sf::VideoMode( display.width, display.height),
                   title, styles, settings);

  // TODO : assert resolution is correct in Fullscreen mode
  
  setVerticalSync(false);
  
  gl::Initialize();
}    

void Window::setTitle(const char *title) 
{ 
  m_handle.setTitle( title ); 
}

void Window::setPosition(const int x, const int y) 
{ 
  m_handle.setPosition(sf::Vector2i(x, y)); 
}

void Window::resize(const unsigned int width, const unsigned int height)
{
  if ((width != m_display.width) || (height != m_display.height)) 
  {
    m_display.width = width;
    m_display.height = height;
    m_handle.setSize(sf::Vector2u( width, height)); 
    gl::State::SetViewport( 0, 0, width, height); // ~
  }
}

void Window::setVerticalSync(bool status)
{
  m_handle.setVerticalSyncEnabled(status);
}

void Window::close()
{
  m_bClosed = true;
  m_handle.close();
}

bool Window::pollEvent(sf::Event &ev) 
{
  return m_handle.pollEvent(ev);
}

void Window::swap() 
{ 
  m_handle.display(); 
}

  
} // aer
